package com.plum.admin.config.security;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.plum.admin.common.exception.LoginFailLimitException;
import com.plum.admin.modules.sys.entity.SysUser;
import com.plum.admin.modules.sys.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * TODO
 *
 * @author 子丶沫
 * @version 1.0
 * @date 2021/8/13 11:46
 */
@Component
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {
    private final ISysUserService userService;
    private  final StringRedisTemplate redisTemplate;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String flagKey = "loginFailFlag:" + username;
        String value = redisTemplate.opsForValue().get(flagKey);
        Long timeRest = redisTemplate.getExpire(flagKey, TimeUnit.MINUTES);
        if (StrUtil.isNotBlank(value)) {
            // 超过限制次数
            throw new LoginFailLimitException("登录错误次数超过限制，请" + timeRest + "分钟后再试");
        }
        SysUser user = userService.findByUsername(username);
        if(ObjectUtil.isNull(user)){
            throw new UsernameNotFoundException(String.format("用户名【%s】,不存在",username));
        }
        return new SecurityUserDetails(user.getId(),user.getUsername(),user.getPassword(),user.getPermissionList(),user.getLockFlag());
    }
    public UserDetails loadUserByMobile(String mobile){
        SysUser user = userService.findByUserMobile(mobile);
        if(ObjectUtil.isNull(user)){
            throw new UsernameNotFoundException(String.format("手机号码【%s】,不存在",mobile));
        }
        return new SecurityUserDetails(user.getId(),user.getUsername(),user.getPassword(),user.getPermissionList(),user.getLockFlag());
    }

}
